package app

import (
	"barge/pkg/manager"
	"barge/pkg/util"
	"github.com/pelletier/go-toml/v2"
	"os"
)

type ConfigManager struct {
	*manager.Config
	Path string
}

func NewConfigManager(filePath string) (*ConfigManager, error) {
	m := &ConfigManager{
		Config: new(manager.Config),
		Path:   filePath,
	}
	err := m.LoadConfig()
	if err != nil {
		return nil, err
	}
	m.Tidy()
	return m, nil
}

func (m *ConfigManager) LoadConfig() error {
	if !util.IsFileExists(m.Path) {
		f, err := os.Create(m.Path)
		if err != nil {
			return err
		}
		defer f.Close()
		return nil
	}
	f, err := os.Open(m.Path)
	if err != nil {
		return err
	}
	defer f.Close()
	return toml.NewDecoder(f).Decode(m.Config)
}

func (m *ConfigManager) Save() error {
	f, err := os.Create(m.Path)
	if err != nil {
		return err
	}
	defer f.Close()
	return toml.NewEncoder(f).Encode(m.Config)
}
